package com.zlyx.easy.core.maven;

import java.io.File;
import java.io.FileReader;

import org.apache.maven.model.Model;
import org.apache.maven.model.Scm;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;

import com.zlyx.easy.core.app.AppUtils;
import com.zlyx.easy.core.utils.StringUtils;

/**
 * @Auth 赵光
 * @Describle
 * @2019年6月25日 下午4:33:58
 */
public final class MavenUtils {

	private static Model model;

	public static Model getModel() {
		if (model == null) {
			model = new Model();
			try {
				handleMaven();
			} catch (Exception e) {
			}
		}
		notNullModel();
		return model;
	}

	private static void notNullModel() {
		if (StringUtils.isEmpty(model.getVersion())) {
			if (model.getParent() != null) {
				model.setVersion(model.getParent().getVersion());
			} else {
				model.setVersion("0.0.1-SNAPSHOT");
			}
		}
		if (StringUtils.isEmpty(model.getUrl())) {
			model.setUrl("https://gitee.com/xiaoyudeguang/easy-swagger.");
		}
		if (StringUtils.isEmpty(model.getDescription())) {
			model.setDescription("An useful tool for java developers when using swagger.");
		}
		if (StringUtils.isEmpty(model.getName())) {
			model.setName(AppUtils.getMainClass().getSimpleName());
		}
		if (model.getScm() == null) {
			model.setScm(new Scm());
		}
		if (StringUtils.isEmpty(model.getGroupId()) && model.getParent() != null) {
			model.setGroupId(model.getParent().getGroupId());
		}
	}

	private static boolean handleMaven() throws Exception {
		MavenXpp3Reader reader = new MavenXpp3Reader();
		String myPom = System.getProperty("user.dir") + File.separator + "pom.xml";
		if (new File(myPom).exists()) {
			model = reader.read(new FileReader(myPom));
			return true;
		}
		return false;
	}
}
